package com.yc.bbs.controller;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import com.yc.bbs.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.yc.bbs.entity.Result;
import com.yc.bbs.entity.User;
import com.yc.bbs.service.BizException;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.servlet.ModelAndView;

/**
 * <p>
 * BBS论坛-用户表-6 前端控制器
 * </p>
 *
 * @author ly
 * @since 2024-11-23
 */
@RestController
@RequestMapping("/user")
public class UserController {

	@Autowired
	IUserService userService;
	
	@RequestMapping("login")
	public Result login(@Valid User user, Errors errors, HttpSession session) throws BizException {
		if (errors.hasFieldErrors("uname") || errors.hasFieldErrors("upass")) {
			throw new BizException("",errors.getAllErrors());
		}
		try{
			User dbUser = userService.login(user);
			session.setAttribute("myinfo",dbUser);
		} catch (BizException e){
			// 添加自定义的错误信息
			errors.rejectValue("uname", "uname or upass error", e.getMessage());
			// 给业务异常添加错误
			e.setData(errors.getAllErrors());
			throw e;
		}
		return new Result(1,"登录成功",null);
	}

	@RequestMapping("myinfo")
	public Result myinfo(@SessionAttribute(required = false) User myinfo) throws BizException {
		if(myinfo == null){
			throw new BizException("未登录", null);
		}
		return new Result(1, "已登录", myinfo);
	}

	@RequestMapping("logout")
	public ModelAndView logout(HttpSession session, ModelAndView mav){
		session.invalidate(); // 会话失效
		mav.setViewName("redirect:/index.html");
		return mav;
	}
	

}
